import asyncio
import threading
import time


class AsyncHelper:
    def __init__(self):
        self.loop = asyncio.new_event_loop()
        self.thread = threading.Thread(target=self._run_loop, daemon=True)
        self.thread.start()

    def _run_loop(self):
        asyncio.set_event_loop(self.loop)
        self.loop.run_forever()

    def run_async(self, coro):
        """在主线程中调用，在异步线程中执行协程并返回结果"""
        future = asyncio.run_coroutine_threadsafe(coro, self.loop)
        return future.result()  # 这会阻塞直到协程完成

    def stop(self):
        self.loop.call_soon_threadsafe(self.loop.stop)


# 示例异步函数
async def async_operation(x, y):
    await asyncio.sleep(1)  # 模拟异步操作
    return x + y


async def async_task():
    await asyncio.sleep(3)
    return f"异步函数 Task completed"


# 使用示例
def main():
    helper = AsyncHelper()

    try:
        # 在主线程中调用异步函数
        result1 = helper.run_async(async_operation(10, 20))
        print(f"结果1: {result1}")

        result2 = helper.run_async(async_task())
        print(f"结果2: {result2}")

        # 批量调用
        results = []
        for i in range(3):
            result = helper.run_async(async_operation(i, i * 10))
            results.append(result)
        print(f"批量结果: {results}")

    finally:
        helper.stop()


if __name__ == "__main__":
    main()
